<template>
    <div>
        <el-page-header content="添加轮播" icon="" title="轮播管理"></el-page-header>
        <el-form
        :model="carouselForm"
        :rules="carouselFormRules"
        ref="carouselFormRef"
        label-width="80px"
        class="demo-ruleForm"
        >
            <el-form-item label="标题" prop="carouselTitle">
                <el-input v-model="carouselForm.carouselTitle"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="carouselAddress">
                <div class="box-card">
                    <img class="the_img" :src="carouselForm.carouselAddress" alt="">
                    <div class="btn-box">
                        <input type="file" accept="image/*" style="display: none" id="iptRef" @change="onFileChange" />
                        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button> 
                    </div>
                </div>
            </el-form-item>             
            <el-button style="margin-left:48%" type="primary" @click="submitForm()">添加轮播</el-button>
        </el-form>
    </div>
</template>

<script setup>
import {ref,reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {addCarouselAPI} from '@/api'

const carouselFormRef=ref()
const carouselForm=reactive({
    carouselTitle:"",
    carouselAddress:""
})



const carouselFormRules=reactive({
    carouselTitle: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    carouselAddress: [{ required: true, message: '请上传图片', trigger: 'blur' }]
    
})
// 添加轮播
const submitForm=()=>{
    carouselFormRef.value.validate(async valid=>{
        if(valid){
            const {data:res}=await addCarouselAPI(carouselForm)          
            if (res.status === 200 && res.message === "OK") {
                ElMessage.success('添加成功')
                return
            } 
            ElMessage.error('添加失败');            
            
        }
    })
}


// 图片
const chooseImg=function () {
    // 模拟点击行为
    document.getElementById('iptRef').click()
  }
const onFileChange=function (e) {
    const files = e.target.files // 拿到用户选择的文件数组
    console.log(files);
    if (files.length === 0) {
     
    } else {
      // 解决方案2：文件->base64字符串（此字符串是可以发给后台的）
      const fr = new FileReader()
      fr.readAsDataURL(files[0]) // 传入文件对象开始读
      fr.onload = (e) => { 
        carouselForm.carouselAddress = e.target.result // 赋予给变量，让他显示在img的src里
      }
    }
  }
</script>

<style lang="scss" scoped>
.demo-ruleForm{
    margin-top: 50px;
}

// 图片
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
.the_img{
    width: 150px;
    height: 150px;
}
</style>